/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.embed.domain.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.cshoo.tattoo.embed.domain.feign.dto.QuerySingleMessageItemResp;
import org.cshoo.tattoo.embed.domain.feign.dto.QuerySingleMessageResp;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import java.util.Optional;

@Service
@Slf4j
public class MessageSdkService {

    @Resource
    private DataCenterService dataCenterService;

    /**
     * 获取message
     *
     * @param code   编号
     * @param params 参数
     * @return message
     * @throws Exception 频繁调用异常
     */
    public String getMessage(String code, Object... params) throws Exception {
        return this.getMessage(code, LocaleContextHolder.getLocale(), params);
    }

    /**
     * 获取message
     *
     * @param code   编号
     * @param locale 语言
     * @param params 参数
     * @return message
     * @throws Exception 频繁调用异常
     */
    public String getMessage(String code, Locale locale, Object... params) throws Exception {
        QuerySingleMessageResp querySingleMessageResp = dataCenterService.querySingleMessage(code);
        String content = querySingleMessageResp.getDefaultContent();
        List<QuerySingleMessageItemResp> querySingleMessageItems = querySingleMessageResp.getQuerySingleMessageItems();
        if (CollectionUtils.isNotEmpty(querySingleMessageItems)) {
            Optional<QuerySingleMessageItemResp> querySingleMessageItemRespOptional = querySingleMessageItems.stream().filter(item -> item.getLang().equals(locale.getLanguage() + "-" + locale.getCountry())).findAny();
            if (querySingleMessageItemRespOptional.isPresent()) {
                content = querySingleMessageItemRespOptional.get().getContent();
            }
        }
        return MessageFormat.format(content, params);
    }

}
